// 所有ajax请求应该引入此类，这样可以全局进行过滤，单独引入不保证axios配置生效
import axios from 'axios'
import {isDemo, isProd, isQa} from './env-process'
import {admin_auth_cookie_key, deleteCookie, getCookie} from './cookie-process.js'

axios.defaults.withCredentials = false // 不要开启，开启的话会有跨域问题，需要配置。我们设置header传输即可，无需传递cookie

export const getRootApi = function (urlRoot) {
  let apiRoot = 'http://localhost:9001' //本地后台接口地址
  if (isQa()) {
    apiRoot = ''
  }
  if (isDemo()) {
    apiRoot = ''
  }
  if (isProd()) {
    apiRoot = ''
  }
  if (urlRoot) {
    apiRoot = apiRoot + urlRoot
  }
  return apiRoot
}

//与上同理，用于websocket连接
// export const getWsRootApi = function (urlRoot) {
//   let apiRoot = 'ws://localhost:9099'
//   if (process.env.NODE_ENV === 'production') {
//     if (process.env.VUE_APP_ENV === 'qa') {
//       apiRoot = 'ws://xxxx.com'
//     } else if (process.env.VUE_APP_ENV === 'demo') {
//       apiRoot = ''
//     } else {
//       apiRoot = ''
//     }
//   }
//   if (urlRoot) {
//     apiRoot = apiRoot + urlRoot
//   }
//   return apiRoot
// }

//获取rest api相关
function getRestPromise(url, params, method) {
  return new Promise((resolve, reject) => {
    axios[method](getRootApi(url), params).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export const get = function (url, params) {
  return getRestPromise(url, {params: params}, 'get')
}
export const del = function (url, params) {
  return getRestPromise(url, {params: params}, 'delete')
}
export const post = function (url, params) {
  return getRestPromise(url, params, 'post')
}
export const put = function (url, params) {
  return getRestPromise(url, params, 'put')
}

// 请求之前,可以封装header，将token放入header中传递，具体根据鉴权方式自己设定
axios.interceptors.request.use(request => {
  let auth_header = getCookie(axios.ctx, admin_auth_cookie_key)
  console.log(request.method, request.url, request.params, process.env.NODE_ENV, process.env.VUE_APP_ENV, auth_header)
  if (auth_header) {
    request.headers[admin_auth_cookie_key] = auth_header
  }
  //console.log(request.headers)
  return request
}, err => {
  return Promise.reject(err)
})

axios.interceptors.response.use(response => {
  console.log(response.data)
  return response
}, err => {
  console.error(err)
  goLogin(err && err.response && err.response.data ? err.response.data.code : 0)
  return Promise.reject(err)
})

//这里可以根据返回值确定是否需要重新登录
function goLogin(code) {
  // after
  if (code === 403) {
    deleteCookie(axios.ctx, admin_auth_cookie_key)
    axios.router.$$redirect('/login')
  }
}

//初始化,这里直接注入到axios中，不要将上面的拦截写在这个方法里，这样会导致每一次ssr，都会新创建拦截器，导致访问很多次接口
export const axiosInit = function (ctx, router) {
  axios.ctx = ctx
  axios.router = router
}